<?php

namespace app\admin\model;

use app\common\model\BaseModel;
use app\common\model\Tenant;
use think\Db;

class Tenantdistributiontype extends BaseModel
{
    const Type_1 = 1;//配送方式  1 到店自取，2 物流配送;
    const Type_2 = 2;

    const STATUS_1 = 1; //是否启用  1启用  0不启用
    const STATUS_0 = 0;

    const APP_TYPE_1 = 1;   //适用门店 1 所有门店 2指定门店
    const APP_TYPE_2 = 2;

    const DELIVERMETHOD_0 = 0; //配送方式   0=物流配送  1=自行配送 2=达达配送 3=到店自取
    const DELIVERMETHOD_1 = 1;
    const DELIVERMETHOD_2 = 2;
    const DELIVERMETHOD_3 = 3;

    public function updateDeliverMethod($data){
        $tenantDistributionId = $data['tenantDistributionId'];
        $data['updateDate'] = date("Y-m-d h:i:s",time());
        unset($data['tenantDistributionId']);
        $res = self::where('id','=',$tenantDistributionId)->update($data);

        return $res;
    }

    public function getTdtStore(){
        return $this->hasMany('tenantdistributionlinkstore','tenantDistributionId','id');
    }


    public function getTentanTypes($tentanId){

        return $this->where('tenantId','=',$tentanId)->select();
    }

    /**
     * @param $status
     * @param $applicableType
     * @param $type_id
     * @param $packingCharge
     * 修改商品配送
     */
    public function updateTdtType($status,$applicableType,$type_id,$packingCharge){
        $updateDate = date('Y-m-d h:i:s');
        $user = session('member');
        return self::where("id","=",$type_id)->update([
            'status'=>$status,
            'applicableType'=>$applicableType,
            'packingCharge'=>$packingCharge,
            'updateDate'=>$updateDate,
            'updateOper'=>$user['id']
        ]);
    }

    /**
     * @param $tenantId
     * @return bool
     * 商户设置配送方式
     */
    public function add_setting($tenantId){
        //判断用户是否设置过配送
        $tentanModel = new Tenant();
        $is_tdt = $tentanModel->where("id","=",session('TENANT_ID'))->field('is_tdt')->find();

        session('is_tdt',$is_tdt);
        $is_tdt = session('is_tdt');
        $is_tdtArr = json_decode($is_tdt,true);
        if($is_tdtArr['is_tdt']){
           return false;
        }

        $arr1 = array(
            "tenantdistribution"=>"到店自取",
            "distributionType"=>self::Type_1
        );
        $arr2 = array(
            "tenantdistribution"=>"物流配送",
            "distributionType"=>self::Type_2
        );
        $date = date('Y-m-d h:i:s',time());
        $user = session("member");
        $id = get_uniqid_id();
        $res = self::insert([
            "id"=>$id,
            "tenantId"=>$tenantId,
            "status"=>self::STATUS_0,
            "tenantdistribution"=>$arr1['tenantdistribution'],
            "createDate"=>$date,
            "createOper"=>$user['id'],
            "updateOper"=>"",
            "applicableType"=>self::APP_TYPE_1,
            "distributionType"=>$arr1['distributionType'],
            "packingCharge"=>0,
        ]);

        $arr[] = $res;
        $arr['id1'] = $id;

        if($res){
            $id = get_uniqid_id();
            $arr['id2'] = $id;
            $res = self::insert([
                "id"=>$id,
                "tenantId"=>$tenantId,
                "status"=>self::STATUS_1,
                "tenantdistribution"=>$arr2['tenantdistribution'],
                "createDate"=>$date,
                "createOper"=>$user['id'],
                "updateOper"=>"",
                "applicableType"=>self::APP_TYPE_1,
                "distributionType"=>$arr2['distributionType'],
                "packingCharge"=>0,
                'deliverMethod' => 1
            ]);
            $arr[] = $res;
        }

        if($res){
            //初始化物流系统
            $this->initlogistics($tenantId,$arr['id2']);
            $tenantModel =  new Tenant();
            $res = $tenantModel->where('id',"=",$tenantId)->update(['is_tdt'=>$tenantModel::IS_TDT_1]);
        }

        return $res;
    }

    private function initlogistics($tenantId,$tid){
        $distanceIncrease = '{"distanceIncrease_1_3":"1_3","distanceIncrease_1_3_val":100,"distanceIncrease_3_5":"3_5","distanceIncrease_3_5_val":100}';
        $nocturnalPriceIncrease = '{"nocturnalPriceIncrease_22_08":"22_08","nocturnalPriceIncrease_22_08_val":100}';
        $weightIncrease = '{"weightIncrease_1":"1","weightIncrease_1_val":100,"weightIncrease_1_5":"1_5","weightIncrease_1_5_val":100,"weightIncrease_5_10":"5_10","weightIncrease_5_10_val":100}';
        $tenantDistributionId = $tid;
        $tenantId = $tenantId;
        $logistics = new Logistics();
        $logistics->id = get_uniqid_id();
        $logistics->status = 1;
        $logistics->orderStartingPrice = 100;
        $logistics->freight = 100;
        $logistics->packingCharge = 100;
        $logistics->distanceIncrease = $distanceIncrease;
        $logistics->nocturnalPriceIncrease = $nocturnalPriceIncrease;
        $logistics->tenantId = $tenantId;
        $logistics->tenantDistributionId = $tenantDistributionId;
        $logistics->deliverMethod = 1;
        $logistics->weightIncrease = $weightIncrease;
        $logistics->save();
        $logistical = new Logistical();
        $logistical->id = get_uniqid_id();
        $logistical->packingCharge = 100;
        $logistical->freight_type = 0;
        $logistical->status = 1;
        $logistical->tenantDistributionId = $tenantDistributionId;
        $logistical->tenantId = $tenantId;
        $logistical->createTime = date('Y-m-d H:i:s',time());
        if($logistical->save()){
            $logistical_rrule = new LogisticalRrule();
            $logistical_rrule->id = get_uniqid_id();
            $logistical_rrule->unifiedmoney = 100;
            $logistical_rrule->logistical_id = $logistical->id;
            $logistical_rrule->save();
        }
    }

    /**
     * @param $tdtTypeId
     * @return array|false|\PDOStatement|string|\think\Model
     * 查询配送类型
     */
    public function findTdtType($tdtTypeId){
        return self::where("id","=",$tdtTypeId)->find();
    }

    /**
     * @param $tdtTypeId
     * @param $status
     * @return $this
     * 修改当前商户物流配送状态
     */
    public function updateStatus($tdtTypeId,$status){
        return  self::where('id',"=",$tdtTypeId)->update(['status'=>$status]);
    }

    /**
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取商户所有配送设置
     */
    public function findCuTenantTdTypes(){
        $tentanId = session("TENANT_ID");
        return self::where("tenantId","=",$tentanId)->select();
    }


    public function getCurrentStores($type_id){
        $sql = "select store.id id,store.name name from tenantdistributiontype 
        join tenantdistributionlinkstore 
        on tenantdistributiontype.id=tenantdistributionlinkstore.tenantDistributionId
        join store on tenantdistributionlinkstore.storeId = store.id 
        where tenantdistributiontype.id = '{$type_id}'
        and  tenantdistributionlinkstore.status = ".self::STATUS_VALID ;
        $res = Db::query($sql);

        return $res;
    }
}